<template>
  <div>
    <xl-spec ref="specRef" :specs="specList" @generate="generateSku" />
    <div class="sku-title">价格</div>
    <div class="table">
      <el-table ref="skuTableRef" :data="skuTable" border>
        <el-table-column
          v-for="spec in specList"
          :key="spec.name"
          :label="spec.name"
          :prop="spec.name"
          align="center"
          width="160"
        >
          <template #default="scope">
            {{ scope.row[spec.name] }}
          </template>
        </el-table-column>
        <el-table-column key="price" label="成本价" prop="price" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.price" placeholder="请输入成本价">
              <template #append>元</template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" style="display: block" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              size="small"
              link
              :icon="Delete"
              style="color: #F56C6C"
              @click="deleteSku(scope.row, scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import {Delete} from '@element-plus/icons-vue'
import XlSpec from '@/components/Tools/XlSpec.vue'
import {priceToFen} from "@/utils/index.js"

// 定义 props
const props = defineProps({
  specs: {
    type: [String, Array],
    default: () => []
  },
  skus: {
    type: [String, Array],
    default: () => []
  },
  openStock: {
    type: Boolean,
    default: true
  }
})

// 响应式引用
const specRef = ref(null)
const skuTableRef = ref(null)
const skuTable = ref([])
const specList = ref([])


// 解析 specs 和 skus
const parseJsonOrArray = (val) => {
  if (typeof val === 'string' && val) {
      const arr = JSON.parse(val)
    return  Array.isArray(arr) ? arr : []
  }
  return Array.isArray(val) ? val : []
}

// 监听 specs 变化
watch(() => props.specs, (newVal) => {
  specList.value = parseJsonOrArray(newVal)
}, { immediate: true })

// 监听 skus 变化
watch(() => props.skus, (newVal) => {
  skuTable.value = parseJsonOrArray(newVal)
}, { immediate: true })

// 重置方法
const reset = () => {
  specList.value = []
  skuTable.value = []
}

// 删除 SKU
const deleteSku = (row, index) => {
  skuTable.value.splice(index, 1)
}

// 生成 SKU
const generateSku = (specLists) => {
  // 确保 specLists 是有效的数组
  if (!specLists || !specLists.length) {
    specList.value = []
    skuTable.value = []
    return
  }

  specList.value = specLists
  if (skuTable.value.length) {
    $xl.modal.confirm('刷新列表会导致sku信息重新生成，是否要继续生成？').then(() => {
      skuTable.value = generateTable(skuAssemblyData(specList.value))}).catch(() => {})
  } else {
    skuTable.value = generateTable(skuAssemblyData(specList.value))
  }
}
// SKU 数据组装
const skuAssemblyData = (arrT) => {
  return getSkuData(generateTableColumn(arrT))
}

// 获取 SKU 数据
const getSkuData = (arr) => {
  let res = [[]]
  arr.map(item => {
    const s = []
    res.map(v => {
      item.map(ele => {
        s.push([...v, ele])
      })
    })
    res = s
  })
  return res
}

// 生成表格列
const generateTableColumn = (arrT) => {
  const arr = []
  // 循环删除二维数组元素中的空数组
  arrT.forEach(item => {
    arr.push(item.values || [])
  })
  return arr
}

// 生成表格
const generateTable = (arr) => {
  const table = []
  arr.forEach(item => {
    table.push(generateTableItem(item))
  })
  return table
}

// 生成表格项
const generateTableItem = (item) => {
  const obj = {}
  item.forEach((v, i) => {
    obj[specList.value[i].name] = v
  })
  obj.price = 0
  obj.status = '0'
  return obj
}

// 提交方法
const submit = () => {
  return {
    specs: specList.value,
    skus: skuTable.value.map(sku => {
      const obj = {}
      const specs = {}
      specList.value.forEach(spec => {specs[spec.name] = sku[spec.name]})
      obj.spec = JSON.stringify(specs)
      obj.price = priceToFen(sku.price)
      obj.scopePrice = priceToFen(sku.scopePrice)
      obj.status = sku.status
      return obj
    })
  }
}

// 暴露方法
defineExpose({
  reset,
  submit
})
</script>

<style scoped lang="scss">
.sku-title {
  padding: 10px 20px;
  font-weight: 700;
  font-size: 20px;
  margin-top: 70px;
}

.table {
  padding: 0 20px 40px;
}
</style>
